<!-- 物料 -->
<template>
	<el-drawer v-model="isShowDrawer" direction="rtl" :before-close="handleClose" :size="curDrawerSize" :close-on-click-modal="isReadOnly">
		<template #header="{ titleId, titleClass }">
			<div class="zs-drawer-header" :id="titleId" :class="titleClass">
				<i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
				<div class="zs-title zs-text-black">清单</div>
			</div>
		</template>

		<template #default>
			<el-container class="zs-drawer-container">
				<el-scrollbar class="zs-drawer-content">
					<!-- card1 -->
					<div class="zs-align-center zs-space-bottom" id="sm-drawer-demo-card-01">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">清单</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form1" label-position="right" label-width="100px" :rules="rules.rules1" :model="formData.data">
							<el-form-item label="一级分类：" prop="level1">
								<el-select v-model="formData.data.level1" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="isReadOnly" filterable @change="getClassificationDownFn('second', 'action')">
									<el-option v-for="item in classificationDown.first" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item label="二级分类：" prop="level2">
								<el-select v-model="formData.data.level2" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="isReadOnly" filterable @change="getClassificationDownFn('third', 'action')">
									<el-option v-for="item in classificationDown.second" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item label="三级分类：" prop="level3">
								<el-select v-model="formData.data.level3" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="isReadOnly" filterable @change="getClassificationDownFn('inventoryList', 'action')">
									<el-option v-for="item in classificationDown.third" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
							<el-form-item label="清单名称：" prop="inventoryId">
								<el-select v-model="formData.data.inventoryId" class="zs-full-item" :placeholder="isReadOnly ? ' ' : '请选择'" :disabled="isReadOnly" filterable @change="setInventory">
									<el-option v-for="item in classificationDown.inventoryList" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-form>
					</div>
				</el-scrollbar>
				<hsDocWrapper :nodeList="curNodeList" />
			</el-container>
		</template>

		<template v-if="handleType != 'info'" #footer>
			<div>
				<el-button class="zs-btn-md zs-btn-primary" @click="doConfirm">提交</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
	import { getInventoryApi } from '@/api/common.js';
	import { suppliesAddApi } from '@/api/supplies.js';
	import { ElMessage } from 'element-plus';
	import { ref, reactive, watch, nextTick } from 'vue';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';
	import { setFormSelectOptions } from '@/utils/formEvent';

	const route = useRoute();

	const props = defineProps({
		isShow: { type: Boolean, default: false },
		isReadOnly: { type: Boolean, default: true },
		handleType: { type: String, default: '' },
		currentRow: { type: Object },
	});

	let store = useStore();
	const curDrawerSize = ref(store.state.uiDrawerSize);

	const emit = defineEmits(['close']);

	let isShowDrawer = ref(props.isShow);

	let formData = reactive({ data: { } });

	const curNodeList = ref([
		{ name: '清单', id: 'sm-drawer-demo-card-01' },
	]);

	const form1 = ref();
    const forms = [form1];

    // 三级分类
	let classificationDown = reactive({
		first: [],
		second: [],
		third: [],
		inventoryList: [],
	});

    const rules = reactive({
		rules1: {
			level1: [{ required: true, message: '请选择一级分类', trigger: 'change' }],
			level2: [{ required: true, message: '请选择二级分类', trigger: 'change' }],
			level3: [{ required: true, message: '请选择三级分类', trigger: 'change' }],
			inventoryId: [{ required: true, message: '请选择清单名称', trigger: 'change' }],
		}
	});

	watch(
		() => props.isShow,
		(newVal, oldVal) => {
			isShowDrawer.value = newVal;
			nextTick(() => {
				newVal && props.handleType == 'add' && initForm();
			});
		},
	);

	//提交
	const doConfirm = async () => {
		const validatePromises = forms.map(form => new Promise(resolve => form.value.validate(resolve)));
		Promise.all(validatePromises).then(async results => {
			const isValid = results.every(valid => valid);
			if (isValid) {
				formData.data.projectCode = route.query.projectCode;
				let res = await suppliesAddApi(formData.data);
				if (res.data.code !== 200) return;
				ElMessage({
					message: '提交成功',
					type: 'success',
				});
				isShowDrawer.value = false;
				emit('close', { isShow: false, isRefresh: true });
			}
		});
	};

	//关闭抽屉
	const handleClose = done => {
		emit('close', { isShow: false });
		done();
	};

	//表单初始化
	const initForm = () => {
		formData.data = {}
        const forms = [form1];
		forms.forEach(form => {
			form.value.resetFields();
		});
		let existCreate = curNodeList.value.find(item => item.id === 'create-user-info');
		existCreate && curNodeList.value.pop();
	};

    //三级分类 | 清单名称
	const getClassificationDownFn = async (type = 'first', action) => {
		let params = {};
		if (type == 'second' && action == 'action') {
			initAffectFiled('level2', 'second');
			initAffectFiled('level3', 'third');
			initAffectFiled('inventoryId', 'inventoryList');
		} else if (type == 'third' && action == 'action') {
			initAffectFiled('level3', 'third');
			initAffectFiled('inventoryId', 'inventoryList');
		} else if (type == 'inventoryList' && action == 'action') {
			initAffectFiled('inventoryId', 'inventoryList');
		}
		setTimeout(function () {
			action == 'action' && clearClassValidate();
		}, 30);

		params.classify1 = ['inventoryList', 'third', 'second'].includes(type) ? formData.data.level1 : '';
		params.classify2 = ['inventoryList', 'third'].includes(type) ? formData.data.level2 : '';
		params.classify3 = ['inventoryList'].includes(type) ? formData.data.level3 : '';

		let res = await getInventoryApi(params);
		let resData = res.data;
		if (resData.code == 200) {
			classificationDown[type] = resData.data;
		}
	};

    //级联选择变化时清空下选的被动项
	const initAffectFiled = (fieldName, listName) => {
		formData.data[fieldName] = '';
		classificationDown[listName] = [];
	};

    const clearClassValidate = () => {
		form1.value.clearValidate('level2');
		form1.value.clearValidate('level3');
		form1.value.clearValidate('inventoryId');
	};

	const setInventory = (val) => {
		let target = classificationDown.inventoryList.find(item => item.id == val)
		if (!target) return
		formData.data.inventoryCode = target.number
		formData.data.inventoryName = target.name

	}

	getClassificationDownFn('first', '');
</script>
